namespace SimpleWebServices
{
    using System;
    using System.Globalization;
    using System.IO;
    using System.Runtime.Serialization.Formatters.Soap;
    using System.Text;
    using System.Xml.Serialization;

    public static class StringExtensionMethods
    {
        public static T Deserialize<T>(this string xml)
        {
            return (T)Deserialize(xml, typeof(T));
        }

        public static object Deserialize(this string xml, Type type)
        {
            if (null == xml)
            {
                throw new ArgumentNullException("xml");
            }
            else if (0 == xml.Length)
            {
                throw new ArgumentOutOfRangeException("xml");
            }
            else if (null == type)
            {
                throw new ArgumentNullException("type");
            }

            object result = null;

            using (MemoryStream stream = new MemoryStream())
            {
                using (StreamWriter writer = new StreamWriter(stream))
                {
                    writer.Write(xml);
                    writer.Flush();
                    stream.Position = 0;

                    if (typeof(Exception).IsAssignableFrom(type))
                    {
                        result = new SoapFormatter().Deserialize(stream);
                    }
                    else
                    {
                        result = new XmlSerializer(type).Deserialize(stream);
                    }
                }
            }

            return result;
        }

        public static string RemoveNonnumericCharacters(this string obj)
        {
            StringBuilder buffer = null;

            if (null != obj)
            {
                buffer = new StringBuilder();

                foreach (char value in obj)
                {
                    if ((48 > (int)value) || (57 < (int)value))
                    {
                        /// this is not a number
                    }
                    else
                    {
                        buffer.Append(value);
                    }
                }
            }

            return (null == buffer) ? null : buffer.ToString();
        }

        public static T ConvertTo<T>(this string value)
        {
            return (T)Convert.ChangeType(value, typeof(T), CultureInfo.InvariantCulture);
        }
    }
}